package com.canbot.u05.activity.customvoice

import android.app.Dialog
import android.content.Intent
import android.os.Bundle
import android.os.Environment
import android.os.Message
import android.support.v7.widget.GridLayoutManager
import android.view.View
import com.alibaba.fastjson.JSON
import com.canbot.u05.R
import com.canbot.u05.activity.*
import com.canbot.u05.activity.customvoice.adapter.CustomDialogAdapter
import com.canbot.u05.activity.customvoice.bean.CustomDialogData
import com.canbot.u05.activity.customvoice.bean.CustomDialogExcelDatas
import com.canbot.u05.activity.customvoice.bean.QuestionBean
import com.canbot.u05.activity.customvoice.tool.CommonDialog
import com.canbot.u05.activity.customvoice.tool.CustomDialogExcelLoader
import com.canbot.u05.activity.customvoice.tool.GridSpacingItemDecoration
import com.canbot.u05.bean.JsonResponse
import com.canbot.u05.socket.IpMsgConst
import com.canbot.u05.socket.MsgSendUtils
import com.canbot.u05.socket.MsgType
import com.canbot.u05.utils.OkHttpUtils
import com.canbot.u05.utils.PathConst
import com.canbot.u05.utils.ToastTools
import com.canbot.u05.widget.LoadingDialogUtils
import kotlinx.android.synthetic.main.activity_custom_dialog.*
import java.io.File
import java.lang.ref.WeakReference
import java.util.*

/**
 * CustomDialogActivity
 * 自定义对话Excel导入
 *
 * @author Liu.Heng
 */
class CustomDialogActivity : BaseActivityNoTitle() {

    private val className = CustomDialogActivity::class.java.name

    private lateinit var mCustomDialogAdapter: CustomDialogAdapter

    private lateinit var mCustomDialogData: MutableList<CustomDialogData>

    private val filePath = Environment.getExternalStorageDirectory().toString() + File.separator

    private lateinit var excelPath: String

    private lateinit var mQuestions: List<String>

    private lateinit var dialogLoading: Dialog

    private val mHandler = getHandler { msg ->

        if (msg.what == 1) {
            dataView()
        }

    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_custom_dialog)
//        mQuestions = ArrayList()
        val mIntent = intent
        mQuestions = JSON.parseArray(mIntent.getStringExtra("data"), String::class.java)
        initView()
    }

    override fun onResume() {
        super.onResume()
        MsgSendUtils.sendStringMsg(MsgType.PLAY_SOUND, PathConst.CUSTOM_DIALOG_PAYH + "u05_pldr_001.wav")
        MsgSendUtils.sendStringMsg(MsgType.EYE_MOTION, "18")
    }

    private fun initView() {
        /**网格布局，每行为4*/
        my_gridView.layoutManager = GridLayoutManager(this, 4)
        my_gridView.addItemDecoration(GridSpacingItemDecoration(4, 120, false))
        mCustomDialogData = ArrayList()
        getData()

        mCustomDialogAdapter = CustomDialogAdapter(this, mCustomDialogData,
                object : CustomDialogAdapter.OnItemClickListener {

                    override fun onItemClick(view: View) {
                        val i = view.tag as Int
                        excelPath = mCustomDialogData[i].path ?: ""
                        mCustomDialogAdapter.checked = i
                        mCustomDialogAdapter.notifyDataSetChanged()
                    }
                })

        my_gridView.adapter = mCustomDialogAdapter

    }

    private fun dataView() {
        mCustomDialogAdapter.notifyDataSetChanged()
    }

    private fun getData() {
        startGetThread()
    }

    private fun startGetThread() {

        Thread().start().run {
            doSearch(filePath)
            val msg = Message()
            msg.what = 1
            msg.obj = 1
            mHandler.sendMessage(msg)
        }
    }

    /****
     * 递归算法获取本地文件
     * @param path 路径
     */
    private fun doSearch(path: String) {
        val file = path.file()

        if (file.exists()) {
            if (file.isDirectory) {
                val fileArray = file.listFiles()
                for (f in fileArray) {

                    if (f.isDirectory) {
                        doSearch(f.path)
                    } else {
                        if (f.name.endsWith(".xls")) {
                            try {
                                val info = CustomDialogData(f.name, f.absolutePath, false)
                                mCustomDialogData.add(info)
                                if (mCustomDialogData.isEmpty()) {
                                    my_relativeLayout1.setVerticalGravity(View.VISIBLE)
                                }
                            } catch (e: Exception) {
                                loge("$className e=${e.message}")
                            }

                        }
                    }
                }
            }
        }
    }

    fun update(customDialogList: ArrayList<CustomDialogExcelDatas>) {


        removeSameData(customDialogList)

        loge("$className ------>$customDialogList")

        if (customDialogList.isEmpty()) {
            ToastTools.newInstance(applicationContext).showText("对话内容已上传，请勿重复提交！或Excel内容格式不对")
        } else {
            /**自动定义对话*/
            updateCustomDialog(customDialogList)
        }

    }

    /**
     * 上传数据
     *
     * @param customDialogList 数据
     */
    private fun updateCustomDialog(customDialogList: ArrayList<CustomDialogExcelDatas>) {

        dialogLoading = LoadingDialogUtils.createLoadingDialog(this, getString(R.string.data_upload))
        dialogLoading.show()

        val size = customDialogList.size

        val url = "http://" + IpMsgConst.CHEST_SOCKET_HOST + ":7755/" + "dialogcustom"
        val hashMap = HashMap<String, Any>(2)
        hashMap["chatCmdQsAsBean"] = JSON.toJSONString(customDialogList)
        hashMap["type"] = "6"
        OkHttpUtils.upLoadFile(url, hashMap, object : OkHttpUtils.OkHttpCallBack {
            override fun onSuccess(result: String) {
                dialogLoading.dismiss()
                val strMsgBean = JSON.parseObject(result, JsonResponse::class.java)

                if (strMsgBean.rc == 0) {
                    runOnUiThread {
                        CommonDialog(this@CustomDialogActivity, R.style.dialog, size.toString()
                                + "条数据," + this@CustomDialogActivity.getString(R.string.upload_complete), true, "查看", object : CommonDialog.OnCloseListener {
                            override fun onClick(dialog: Dialog, confirm: Boolean) {
                                dialog.dismiss()
                                back(null)
                            }
                        }).show()
                    }

                }

            }

            override fun onFailure() {
                runOnUiThread {
                    dialogLoading.dismiss()
                    ToastTools.newInstance(applicationContext).showText(this@CustomDialogActivity.getString(R.string.upload_failed))
                }
            }
        })
    }

    fun back(view: View?) {
        loge("$view")
        finish()
        this.overridePendingTransitionExt()
    }

    fun nextStep(view: View) {
        loge("$view")
        if (mCustomDialogAdapter.checked == -1) {
            ToastTools.newInstance(applicationContext).showText(this.getString(R.string.please_select_dialogue_library))
        } else {
            /**导入Excel文档*/
            CustomDialogExcelLoader(WeakReference(this)).execute(excelPath)
        }
    }

    fun help(view: View) {
        loge("$view")
        startActivity(Intent(this, AddExcelHelpActivity::class.java))
        this.overridePendingTransitionExt()
    }

    private fun removeSameData(customDialogExcelData: ArrayList<CustomDialogExcelDatas>) {
        mQuestions.forEach { question ->
            customDialogExcelData.forEach { customDialogExcelDatas ->
                customDialogExcelDatas.listQsBean.removeIf { mQuestionBean -> mQuestionBean.question == question }
            }
        }
           //继续检测看问题列表是否为空，如果为空，则将整个记录删除.
            customDialogExcelData.removeIf { customDialogExcelDatas -> customDialogExcelDatas.listQsBean.size == 0 }
    }
}

